package com.ybwh.springboot2.common.csrf;

import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@AllArgsConstructor
public class MethodIdempotentCheck implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MethodIdempotentCheck.class);
    private TokenStore tokenStore;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Class<?> clazz = method.getClass();
            if (clazz.isAnnotationPresent(ApiIdempotent.class)) {
                if (!checkToken(request)) {
                    failure(response);
                    return false;
                }
            } else {
                if (method.isAnnotationPresent(ApiIdempotent.class)) {
                    if (!checkToken(request)) {
                        failure(response);
                        return false;
                    }
                }
            }
        }
        return true;
    }

    private void failure(HttpServletResponse response) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("{\"code\": -1, \"message\": \"非法操作\"}");
        response.getWriter().flush();
    }

    private boolean checkToken(HttpServletRequest request) {
        logger.info("验证token");
        String token = request.getParameter("csrf-token");
        if (token == null || token.length() == 0) {
            token = request.getHeader("csrf-token");
        }
        logger.info("获取token：{}", token);
        if (token == null || token.length() == 0) {
            return false;
        }
        return tokenStore.exists(token);
    }

}